<template>
	<el-dialog :title="dataForm.layerManagerId ? '编辑图层' : '创建图层'" width="600" v-model="visible" :close-on-click-modal="false" draggable>
		<el-form ref="layerDialogFormRef" label-position="left" :model="dataForm" :rules="dataRules" label-width="110px" v-loading="loading">
			<el-row :gutter="20">
				<el-col :span="24" class="mb20">
					<el-form-item label="图层名称" prop="layerNameCh">
						<el-input v-model="dataForm.layerNameCh" clearable placeholder="请输入图层名称"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item label="服务类型" prop="serviceType">
						<el-radio-group v-model="dataForm.serviceType" @change="changeServiceType">
							<el-radio-button :label="1">在线图层</el-radio-button>
							<el-radio-button :label="2">静态服务</el-radio-button>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item label="选择文件" prop="storeName">
						<el-row :gutter="20">
							<el-col :span="12">
								<el-select v-model="dataForm.wokeSpaceName" :suffix-icon="IconDropDown" placeholder="选择项目" @change="getFileOptionsByProject">
									<el-option v-for="item in projectOptions" :key="item.value" :label="item.label" :value="item.value" />
								</el-select>
							</el-col>
							<el-col :span="12">
								<el-select v-model="dataForm.storeName" :suffix-icon="IconDropDown" placeholder="选择文件">
									<el-option v-for="item in fileOptions" :key="item.value" :label="item.label" :value="item.value" @click="handleFileChange(item)" />
								</el-select>
							</el-col>
						</el-row>
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item label="所属项目" prop="projectName">
						<el-row :gutter="20">
							<el-col :span="12">
								<el-select v-model="dataForm.projectName" :suffix-icon="IconDropDown" placeholder="选择所属项目" @change="handleProject">
									<el-option v-for="item in projectOptions" :key="item.value" :label="item.label" :value="item.value" />
								</el-select>
							</el-col>
							<!-- <el-col :span="12">
								<el-form-item label="是否启用" prop="status">
									<el-switch v-model="dataForm.status" active-value="1" inactive-value="0" disabled />
								</el-form-item>
							</el-col> -->
						</el-row>
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item label="坐标参考系统" prop="srs">
						<el-row :gutter="20">
							<el-col :span="12">
								<el-select
									filterable
									remote-show-suffix
									remote
									v-model="dataForm.srs"
									:loading="selectLoading"
									:suffix-icon="IconDropDown"
									:remote-method="remoteMethod"
									placeholder="选择坐标参考系统"
								>
									<el-option v-for="item in srsOptions" :key="item.id" :label="item.name" :value="item.name" />
								</el-select>
							</el-col>
							<el-button type="primary" :disabled="filterWorkName" @click="getSrcs">获取数据坐标系统</el-button>
						</el-row>
					</el-form-item>
				</el-col>
				<div v-if="dataForm.serviceType === 1">
					<div class="blue-card">
						<el-text tag="b" size="large">边框计算</el-text>
						<div class="mt10">
							<el-text tag="b" class="mr10">原生边界框</el-text>
							<el-link type="primary" @click="borderCalculation">从数据中计算</el-link>
							<el-row :gutter="20" class="mt10">
								<el-col :span="6">
									<el-text>最小X</el-text>
									<el-input v-model="dataForm.boxMinX" disabled></el-input>
								</el-col>
								<el-col :span="6">
									<el-text>最小Y</el-text>
									<el-input v-model="dataForm.boxMinY" disabled></el-input>
								</el-col>
								<el-col :span="6">
									<el-text>最大X</el-text>
									<el-input v-model="dataForm.boxMaxX" disabled></el-input>
								</el-col>
								<el-col :span="6">
									<el-text>最大Y</el-text>
									<el-input v-model="dataForm.boxMaxY" disabled></el-input>
								</el-col>
							</el-row>
						</div>
						<!-- <div class="mt10">
							<el-text tag="b" class="mr10">经纬度边框</el-text>
							<el-link type="primary" @click="LatLonCalculation">从数据中计算</el-link>
							<el-row :gutter="20" class="mt10">
								<el-col :span="6">
									<el-text>最小X</el-text>
									<el-input v-model="dataForm.latLonBoxMinX" disabled></el-input>
								</el-col>
								<el-col :span="6">
									<el-text>最小Y</el-text>
									<el-input v-model="dataForm.latLonBoxMinY" disabled></el-input>
								</el-col>
								<el-col :span="6">
									<el-text>最大X</el-text>
									<el-input v-model="dataForm.latLonBoxMaxX" disabled></el-input>
								</el-col>
								<el-col :span="6">
									<el-text>最大Y</el-text>
									<el-input v-model="dataForm.latLonBoxMaxY" disabled></el-input>
								</el-col>
							</el-row>
						</div> -->
					</div>
				</div>

				<el-col :span="24" class="mb20">
					<el-form-item label="图层样式" prop="styleName">
						<el-row :gutter="20">
							<el-col :span="12">
								<el-select v-model="dataForm.styleName" :suffix-icon="IconDropDown" placeholder="选择图层样式" clearable>
									<el-option v-for="item in styleOptions" :key="item.value" :label="item.label" :value="item.value" />
								</el-select>
							</el-col>
						</el-row>
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item label="图层说明" prop="layerRemarks">
						<el-input v-model="dataForm.layerRemarks" clearable placeholder="请输入图层说明"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.publish') }}</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="layerDialog">
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';
import { useUserInfo } from '/@/stores/userInfo';
import { fileDataSourceObj, getStyle } from '/@/api/project';
import { addGeoLayer, getInfoById, updateGeoLayer, getBorderCalculation, getGeoBoxLatLonData } from '/@/api/resource/layerManagement';
import { getCoordinatelist, getGeoLayer } from '/@/api/project';
import { getOptName } from '/@/utils/arrayOperation';
import DropDown from '/@/assets/icons/drop-down.svg';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const { t } = useI18n();
// 引入组件

// 定义变量内容
const isInit = ref(false);
const visible = ref(false);
const loading = ref(false);
const selectLoading = ref(false);
const layerDialogFormRef = ref();
const srsOptions = ref<any[]>([]);
const dataType = ref<any[]>([
	{ text: '矢量数据shp', value: 1 },
	{ text: '栅格数据', value: 2 },
	{ text: '3D数据', value: 3 },
]);
const fileOptions = ref<any[]>([]);
const styleOptions = ref<any[]>([]);
const coorForm = ref({
	size: 100,
	current: 1,
	name: '',
});
const projectOptions = computed(() => {
	return useUserInfo().userInfos.projectList;
});
const filterWorkName = computed(() => {
	if (dataForm.wokeSpaceName && dataForm.storeName) {
		return false;
	} else {
		return true;
	}
});
function getSrcs() {
	getGeoLayer({ wokeSpaceName: dataForm.wokeSpaceName, storeName: dataForm.storeName }).then((res) => {
		let { data } = res;
		dataForm.srs = data;
	});
}
// 定义需要的数据
const dataForm = reactive({
	layerManagerId: '',
	layerNameCh: '',
	serviceType: 1,
	wokeSpaceName: '',
	storeName: '',
	dataType: '',
	projectName: '',
	status: '1',
	srs: '',
	boxMinX: '',
	boxMinY: '',
	boxMaxX: '',
	boxMaxY: '',
	latLonBoxMinX: '',
	latLonBoxMinY: '',
	latLonBoxMaxX: '',
	latLonBoxMaxY: '',
	styleName: '',
	layerRemarks: '',
	layerName: '',
	createBy: '',
	projectNameCh: '',
	publishStatus: '',
	createTime: '',
});

const IconDropDown = {
	render: () => {
		return h('img', { src: DropDown });
	},
};

// 表单校验规则
const dataRules = reactive({
	layerNameCh: [{ required: true, message: '图层名称不能为空', trigger: 'blur' }],
	serviceType: [{ required: true, message: '服务类型不能为空', trigger: 'blur' }],
	storeName: [{ required: true, message: '选择文件不能为空', trigger: 'blur' }],
	projectName: [{ required: true, message: '所属项目不能为空', trigger: 'blur' }],
	srs: [{ required: true, message: '坐标系不能为空', trigger: 'blur' }],
	layerRemarks: [{ required: true, message: '样式说明不能为空', trigger: 'blur' }],
});

// 根据项目获取文件列表
const getFileOptionsByProject = async (projectName: any) => {
	if (!isInit.value) dataForm.storeName = '';
	const { data } = await fileDataSourceObj({ projectName: projectName, serviceType: dataForm.serviceType });
	fileOptions.value = data.map((item: any) => {
		return {
			label: `${item.fileNameCh}(${getOptName(dataType.value, item.dataType)})`,
			dataType: item.dataType,
			value: item.fileDataName,
		};
	});
};
async function handleProject(projectName: any) {
	const { data } = await getStyle({ projectName });
	styleOptions.value = data.map((item: any) => {
		return {
			label: item.styleNameCh,
			value: item.styleName,
		};
	});
}

const handleFileChange = (value: any) => {
	dataForm.dataType = value.dataType;
};

// 边框计算
const borderCalculation = async () => {
	try {
		loading.value = true;
		const { data } = await getBorderCalculation({ wokeSpaceName: dataForm.wokeSpaceName, storeName: dataForm.storeName });
		dataForm.boxMinX = data.boxMinx;
		dataForm.boxMinY = data.boxMiny;
		dataForm.boxMaxX = data.boxMaxx;
		dataForm.boxMaxY = data.boxMaxy;
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};
// 获取坐标系方法
function remoteMethod(val) {
	selectLoading.value = true;
	coorForm.value.name = val;
	setTimeout(() => {
		getCoordinatelist(coorForm.value).then((res) => {
			let { data } = res;
			srsOptions.value = data.records;
			selectLoading.value = false;
		});
	}, 1000);
}
// 经纬度计算
const LatLonCalculation = async () => {
	try {
		loading.value = true;
		const { data } = await getGeoBoxLatLonData({
			srs: dataForm.srs,
			boxMinx: dataForm.boxMinX,
			boxMiny: dataForm.boxMinY,
			boxMaxx: dataForm.boxMaxX,
			boxMaxy: dataForm.boxMaxY,
		});
		dataForm.latLonBoxMinX = data.boxMinx;
		dataForm.latLonBoxMinY = data.boxMiny;
		dataForm.latLonBoxMaxX = data.boxMaxx;
		dataForm.latLonBoxMaxY = data.boxMaxy;
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 打开弹窗
const openDialog = (type: string, row?: any) => {
	dataForm.wokeSpaceName = '';
	visible.value = true;
	getCoordinatelist(coorForm.value).then((res) => {
		let { data } = res;
		srsOptions.value = data.records;
	});
	nextTick(async () => {
		layerDialogFormRef.value?.resetFields();
		if (type === 'edit') {
			getLayerInfo(row.layerManagerId);
			handleProject(row.nameSpace);
		} else if (type === 'add') {
			dataForm.layerManagerId = '';
			dataForm.wokeSpaceName = '';
			dataForm.layerName = '';
			dataForm.createBy = '';
			dataForm.projectNameCh = '';
			dataForm.publishStatus = '';
			dataForm.createTime = '';
		}
	});
};

function changeServiceType(val: type) {
	projectOptions.value = [];
	styleOptions.value = [];
	dataForm.wokeSpaceName = '';
	dataForm.styleName = '';
}
// 初始化表单数据
const getLayerInfo = (id: string) => {
	isInit.value = true;
	// 获取数据
	getInfoById(id)
		.then((res: any) => {
			Object.assign(dataForm, res.data);
			getFileOptionsByProject(dataForm.wokeSpaceName);
		})
		.finally(() => {
			isInit.value = false;
		});
};

// 保存数据
const onSubmit = async () => {
	const valid = await layerDialogFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		dataForm.layerManagerId ? await updateGeoLayer(dataForm) : await addGeoLayer(dataForm);

		useMessage().success(t(dataForm.layerManagerId ? 'common.editSuccessText' : 'common.publishSuccessText'));
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

watch(
	() => dataForm.storeName,
	() => {
		if (!isInit.value) {
			dataForm.boxMinX = '';
			dataForm.boxMinY = '';
			dataForm.boxMaxX = '';
			dataForm.boxMaxY = '';
			dataForm.latLonBoxMinX = '';
			dataForm.latLonBoxMinY = '';
			dataForm.latLonBoxMaxX = '';
			dataForm.latLonBoxMaxY = '';
		}
	}
);

// 暴露变量 只有暴漏出来的变量 父组件才能使用
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
:deep(.el-form-item__content) {
	display: block;
}
:deep(.el-radio-button__inner) {
	color: #3156a5;
	background-color: #edf0f7;
	width: 164px !important;
}
.dialog-footer {
	display: flex;
	justify-content: center;
}

.blue-card {
	margin: 5px 5px 20px 5px;
	padding: 10px;
	border-radius: 8px;
	background: #edf0f7;
}
</style>
